<?php

namespace App\Models\Game\Pay\Order;

use App\Models\Game\Model;
use App\Models\Game\Platform\Org;
use App\Models\Elasticsearch\Order\Wallet as EsWallet;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Wallet extends Model
{

    /**
     * 数据表名称
     *
     * @var string
     */
    protected $table = 't_third_wallet_order';

    /**
     * 进行类型转换的字段
     *
     * @var array
     */
    protected $casts = [
        'created' => 'timestamp',
        'updated' => 'timestamp',
        'consume' => 'array',
        'take_back' => 'array',
        'usd' => 'array',
    ];

    /**
     * 状态【创建订单】
     *
     * @var integer
     */
    const STATUS_INIT = 1;

    /**
     * 状态【订单完成】
     *
     * @var integer
     */
    const STATUS_SUCCEED = 2;

    /**
     * 状态【订单已撤销】
     *
     * @var integer
     */
    const STATUS_REVOCATION = 3;

    /**
     * 获得平台信息
     *
     * @return BelongsTo
     */
    public function org(): BelongsTo
    {
        return $this->belongsTo(Org::class, 'plat_code', 'code')->withTrashed();
    }

    /**
     * 获取订单数据
     *
     * @param string $sn
     * @param string|null $platCode
     * @return array|null
     */
    protected function getData(string $sn, ?string $platCode = null): ?array
    {
        if (!config('elasticsearch.default')) {
            $query = $this->newQuery()->where('sn', $sn);

            $data = is_null($platCode) ? $query->first() :
                $query->where('plat_code', $platCode)->first();

            return is_null($data) ? null : $data->toArray();
        } else {
            return EsWallet::getData($sn, $platCode);
        }
    }
}
